package org.school.streaming.net.server.discovery;

import java.net.*;
import java.util.ArrayList;
import java.io.*;

public class DiscoveryHandler {

	private InetAddress localInetAddress;
	private String localHostAddress;
	private String localHostName;

	private File folder;
	private File[] listofFiles;
	private ArrayList<String> fileNames; // ?

	/**
	 * Client that handles discovery registry
	 */
	public DiscoveryHandler() {

		// Get network information from server machine and set fields
		// accordingly
		try {
			getNetworkInfo();
		} catch (UnknownHostException netE) {
			netE.printStackTrace();
		}

		// Get available video file information from server machine and set
		// fields accordingly
		getFiles();

		// Calls PHP script to insert information into database
		try {
			insertAvailable(localHostAddress, fileNames);
		} catch (IOException dbE) {
			dbE.printStackTrace();
		}

	}

	/**
	 * Gets local IP-address and hostname and sets fields accordingly
	 * 
	 * @throws UnknownHostException
	 */
	private void getNetworkInfo() throws UnknownHostException {
		localInetAddress = InetAddress.getLocalHost();
		localHostAddress = localInetAddress.getHostAddress();
		localHostName = localInetAddress.getHostName();
	}

	/**
	 * Gets all files from specified folder and sets field accordingly
	 */
	private void getFiles() {
		folder = new File("resources/movies");
		listofFiles = folder.listFiles();
		fileNames = new ArrayList<String>();

		for (int i = 0; i < listofFiles.length; i++) {
			if (listofFiles[i].isFile()) {
				fileNames.add(listofFiles[i].getName());
			}
		}

	}

	/**
	 * Calls PHP script to insert machine and available video files in database
	 * 
	 * @param machine
	 *            String with name of machine to insert
	 * @param files
	 *            List of filenames of video files to insert
	 * @throws IOException
	 */
	private void insertAvailable(String machine, ArrayList<String> files) throws IOException {

		// Set-up and connect to PHP script
		URL url = new URL("http://localhost/mm_discovery/discovery_insert.php");
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();

		String result = "";

		// Set up HTTP POST string
		StringBuilder sb = new StringBuilder();
		sb.append("status=");
		sb.append(machine);
		sb.append(",");
		for (String s : fileNames) {
			sb.append(s);
			sb.append(",");
		}
		String data = removeLastChar(sb.toString());

		try {
			// Set HTTP connection properties
			connection.setDoInput(true);
			connection.setDoOutput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod("POST");
			connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

			// Do POST
			DataOutputStream dataOut = new DataOutputStream(connection.getOutputStream());
			dataOut.writeBytes(data);
			dataOut.flush();
			dataOut.close();

			// Read result
			BufferedReader in = null;
			try {
				String line;
				in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
				while ((line = in.readLine()) != null) {
					result += line;
				}
			} finally {
				if (in != null) {
					in.close();
				}
			}

		} finally {
			connection.disconnect();
			System.out.println(result);
		}

	}

	/**
	 * Removes last character from POST string because of foreach loop
	 * 
	 * @param s
	 *            String to strip last character from
	 * @return String with last character stripped
	 */
	public String removeLastChar(String s) {
		if (s == null || s.length() == 0) {
			return s;
		}
		return s.substring(0, s.length() - 1);
	}

}
